package com.lantu.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lantu.common.vo.Result;
import com.lantu.sys.entity.Student;
import com.lantu.sys.entity.User;
import com.lantu.sys.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @GetMapping("/all")
    public Result<List<Student>> getAllUser() {
        List<Student> list = studentService.list();
        return Result.success(list, "查询成功");
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(@RequestParam(value = "name", required = false) String name,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize) {

        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name), Student::getName, name)
                .or().
                like(StringUtils.hasLength(name), Student::getStudentNo, name);
        wrapper.orderByDesc(Student::getId);

        Page<Student> page = new Page<>(pageNo, pageSize);
        studentService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);

    }

    @PostMapping
    public Result<?> addUser(@RequestBody Student student) {

        studentService.save(student);
        return Result.success("新增用户成功");
    }

    @PutMapping
    public Result<?> updateUser(@RequestBody Student student) {

        studentService.updateById(student);
        return Result.success("修改用户成功");
    }

    @GetMapping("/{id}")
    public Result<Student> getUserById(@PathVariable("id") Integer id) {
        Student student = studentService.getById(id);
        return Result.success(student);
    }

    @DeleteMapping("/{id}")
    public Result<Student> deleteUserById(@PathVariable("id") Integer id) {
        studentService.removeById(id);
        return Result.success("删除用户成功");
    }
}
